import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken, removeToken } from '@/utils/cookie'
import router from '@/router'

const service = axios.create({
  baseURL: '/dev-api',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 如果存在token，则在请求头中添加token
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 3001) {
      ElMessage.error('登录已过期，请重新登录')
      removeToken()
      router.push('/c-oj/login')
      return Promise.reject(new Error('登录已过期'))
    }
    if (res.code !== 1000) {
      ElMessage.error(res.message || '请求失败')
      return Promise.reject(new Error(res.message || '请求失败'))
    }
    return res
  },
  error => {
    console.log('err' + error)
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

export default service